<?php
/**
 * 个人中心
 * 
 */
namespace frontend\controllers;

use bc\controller\FrontController;
use yii\web\Session;
use bc\ar\MActiveRecord;
use bc\util\Util;
use frontend\models\order\BindModel;
use bc\model\wx\report\ResultModel;
use bc\model\shop\WxUserModel;
use bc\model\wx\report\CodeModel;
use bc\util\Sms;
use bc\model\ecs\UserModel;

class UserController extends FrontController
{
	
	protected $order_url = 'http://wx.zhishimama.com/shop/mobile/admin/order_api.php?act=order_query&page_size=100&user_name=';
	
	protected $shop_base_url = 'http://wx.zhishimama.com/shop/';
	
	/**
	 * 个人中心
	 */
	public function actionIndex()
	{
		//页面授权
		$this->setOAuth();
		$session = new Session();
		$user = $session->get('user');
		
		$view['user'] = $user;
		
		return $this->render('index', $view);
		
	}
	
	
	public function actionOrganization()
	{
		$session = new Session();
		
		$user = $session->get('user');
		$list = [];
		
		if($user)
		{
			$dao = new MActiveRecord();
			
			$list = [];
			//已加入
			$joinSql = 'select * from bc_organization_user as `user` left join bc_organization as o on `user`.organization_id = o.id where user.`user_id_status` = 1 and `user`.user_id = '.$user['id'];
			$join = $dao->getDb()->createCommand($joinSql)->queryAll();
			
			if($join)
			{
				foreach ($join as $item)
				{
					$item['join_info'] = '已入社';
					$item['class'] = 'joined';
					$list[] = $item;
				}
			}
			
			//申请中
			$applySql = 'select * from bc_organization_apply as apply left join bc_organization as o on apply.organization_id = o.id where apply.`user_status` = 1 and apply.user_id = '.$user['id'];
			$apply =  $dao->getDb()->createCommand($applySql)->queryAll();
			if($apply)
			{
				foreach ($apply as $item)
				{
					$item['join_info'] = '已申请';
					$item['class'] = 'waiting';
					$list[] = $item;
				}
			}
			
			$view['list'] = $list;
			
		}
		
		return $this->render('organization', $view);
	}
	
	
	public function actionOrderlist()
	{
		$session = new Session();
		$user = $session->get('user');
		
		if(!$user)
			$this->redirect('/');
		
		//return json data
		$rs = Util::httpGet($this->order_url . $user['openid']);
		$orders = json_decode($rs, true);
		
		foreach ($orders as &$order)
		{
			$order['order_key'] = $order['order_id'];
			switch ($order['shipping_status'])
			{
				case 0:
					$order['status_name'] = '未发货';
					break;
				case 1:
					$order['status_name'] = '已发货';
					break;
				case 2:
					$order['status_name'] = '已收货';
					break;
			}
		}
		
		
		$view = [];
		$view['orders'] = $orders;
		$view['shop_base_url'] = $this->shop_base_url;
		return $this->render('order_list', $view);
	}
	
	
	public function actionOrderdetail()
	{
		$session = new Session();
		$user = $session->get('user');
		
		$id = $this->get('id', 0);
		
		$goods_sn = $this->get('goods_sn', '');
		
		if(!$user || !$id || !$goods_sn)
			$this->redirect('/');
		
		//return json data
		$rs = Util::httpGet($this->order_url . $user['openid']);
		$orders = json_decode($rs, true);
		
		foreach ($orders as $item)
		{
			if($item['order_id'] == $id && $item['goods_sn'] == $goods_sn)
			{
				$order = $item;
				break;
			}
		}
		
		$view = [];
		$view['order'] = $order;
		
		switch ($order['shipping_status'])
		{
			case 0:
				$order['status_name'] = '未发货';
				break;
			case 1:
				$order['status_name'] = '已发货';
				break;
			case 2:
				$order['status_name'] = '已收货';
				break;
		}
		
		$view['shop_base_url'] = $this->shop_base_url;
		return $this->render('order_detail', $view);
	}
	
	
	/**
	 * 我的报告
	 */
	public function actionReport()
	{
		$session = new Session();
		$user = $session->get('user');
		
		if(!$user)
			$this->redirect('/');
		
		$model = new BindModel();
		
		$params = 'bc_order.buyer = "' . $user['openid'] . '"';
		$params .= ' AND bc_order_bind.template_id != 0';
		$list = $model->getReportList($params);
		
		$view = [];
		$view['list'] = $list;
		return $this->render('report', $view);
	}
	
	public function actionReportdetail()
	{
		$id = $this->get('id');
		$session = new Session();
		$user = $session->get('user');
		if(!$id || !$user)
			$this->redirect('/');
		
		$model = new BindModel();
		$row = $model->getRowById($id);
		
		
		$resultModel = new ResultModel();
		$result = $resultModel->getRowById($row['template_id']);
		
		$result['content'] = str_replace('{{$user_name}}', $row['name'], $result['content']);
		
		echo $result['content'];
		
	}
	
	
	/**
	 * 填写用户信息
	 */
	public function actionInfo()
	{
		//页面授权
		$this->setOAuth();
		$session =  new Session();
		$user = $session->get('user');
		
		$openid = $user['openid'];
		$wxUserModel = new WxUserModel();
		$wxUserModel->autoId = 'uid';
		$row = $wxUserModel->getRow(['wxid' => $openid]);
		
		$extra = json_decode($row['extra'], true);
		
		$view['extra'] = $extra;
		
		
		return $this->render('info', $view);
	}
	
	
	/**
	 * 保存用户填写信息
	 */
	public function actionInfosave()
	{
		
		if($this->getRequest()->isPost == true)
		{
			$post = $_POST;
			$session = new Session();
			$user = $session->get('user');
			
			$openid = $user['openid'];
			
			if($post['status'] == 1)
			{
				//是否二胎
				if($post['second_pregnancy'] == 2)
				{
					$post['baby_1_sex'] = '';
					$post['baby_1_date'] = '';
				}

				$post['baby_2_sex'] = '';
				$post['baby_2_date'] = '';
				
				$post['baby_date'] = '';
				$post['baby_sex'] = '';
				$post['two_baby'] = '';
					
				
			}
			else if($post['status'] == 2)
			{
				
				//是否二胎
				if($post['two_baby'] == 1)
				{
					$post['baby_sex'] = '';
					$post['baby_date'] = '';
				}
				else 
				{
					$post['baby_2_sex'] = '';
					$post['baby_2_date'] = '';
					$post['baby_1_sex'] = '';
					$post['baby_1_date'] = '';
				}
				
				$post['second_pregnancy'] = '';
				$post['predict_date'] = '';
			}
			else if($post['status'] == 3)
			{
				$post['baby_1_sex'] = '';
				$post['baby_2_sex'] = '';
				$post['baby_1_date'] = '';
				$post['baby_2_date'] = '';
				$post['baby_date'] = '';
				$post['baby_sex'] = '';
				$post['predict_date'] = '';
				$post['second_pregnancy'] = '';
				$post['two_baby'] = '';
			}
			
			
			$data['extra'] = json_encode($post);
			 
			$wxUserModel = new WxUserModel();
			$wxUserModel->autoId = 'uid';
			$row = $wxUserModel->getRow(['wxid' => $openid]);
			if($row)
			{
				$wxUserModel->modify($data, $row['uid']);
			}
		}
		
		$this->redirect('/user/success');
				
		
	}
	
	public function actionSuccess()
	{
		return $this->render('success');
	}
	
	
	/**
	 * 演示使用
	 */
	public function actionShow()
	{
		$this->redirect('https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx70e4dfb8e0761118&redirect_uri=http%3A%2F%2Fwx.zhishimama.com%2Fuser%2Finfo&response_type=code&scope=snsapi_userinfo&#wechat_redirect');
	}
	
	
	/**
	 * 设置手机号
	 */
	public function actionSetMobile()
	{
		$view['parent_url'] = $_SERVER['HTTP_REFERER'];
		return $this->render('set-mobile', $view);
	}
	
	
	/**
	 * 校验验证码
	 */
	public function actionValidcode()
	{
		$msg ['error'] = 1;
	
		if ($this->getRequest ()->isAjax == true)
		{
				
			$user_name = $this->post ( 'user_name' );
			$mobile = $this->post ( 'mobile' );
			$code = $this->post ( 'code' );
			$parmas ['name'] = $user_name;
			$params ['mobile'] = $mobile;
				
			$codeModel = new CodeModel ();
			$codeModel->sort = 'id DESC';
			$code_row = $codeModel->getList ( [
					'mobile' => $mobile,
					'code' => $code
			] );
			$msg ['data'] = json_encode ( $code_row );
			if (! $code_row [0])
			{
				$msg ['msg'] = '请输入正确的验证码';
			}
			elseif ($code_row [0] ['create_time'] < time () - 60)
			{
				$msg ['msg'] = '验证码已过期';
			}
			else
			{
				$msg ['error'] = 0;
			}
		}
	
		else
		{
			$msg ['msg'] = '请求异常';
		}
	
		echo json_encode ( $msg );
		exit ();
	}
	
	/**
	 * ajax方式发送验证码
	 */
	public function actionSend()
	{
		$msg = [ ];
	
		if ($this->getRequest ()->isAjax == true)
		{
			$user_name = $this->post ( 'user_name' );
			$mobile = $this->post ( 'mobile' );
			$model = new \bc\model\wx\ReportModel ();
			$parmas ['name'] = $user_name;
			$params ['mobile'] = $mobile;
				
			// 创建一个新的验证码
			$arr = [ ];
				
			for($i = 0; $i < 4; $i ++)
			{
				$rand = rand ( 0, 9 );
				$arr [] = $rand;
			}
				
			$code = implode ( '', $arr );
			$data ['code'] = $code;
			$data ['mobile'] = $mobile;
			$data ['create_time'] = time ();
				
			$codeModel = new CodeModel();
			$codeModel->sort = 'id DESC';
			$code_row = $codeModel->getList ( [
					'mobile' => $mobile
			] );
			$codeModel->add ( $data );
				
			// 发送短信验证码
			$sms_msg = '验证码：' . $code . '，本次验证码60s内有效';
			$sms = new Sms ();
			$sms->setMobile ( $mobile );
			$sms->setText ( $sms_msg );
			$result = $sms->send ();
			$msg ['result'] = $result;
			$msg ['msg'] = '验证码已发送!';
		}
		else
		{
			$msg ['msg'] = '请求参数错误！';
		}
	
		echo json_encode ( $msg );
		exit ();
	}
	
	
	/**
	 * 保存手机号
	 */
	public function actionSaveMobile()
	{
		$session = new Session();
		$shop_user = $session->get('shop_user');
		$mobile = $this->post('mobile');
		if($mobile)
		{
			$ecsUserModel = new UserModel();
			$user = $ecsUserModel->getRowById($shop_user['user_id']);
			if(!$user['mobile'] && preg_match('/1\d{10}/', $mobile))
			{
				//更新用户手机信息
				$ecsUserModel->modify(['mobile' => $mobile], $user['user_id']);
			}
		}
		
		
		$this->redirect('/sale/order/quick');
	}
}


